#/usr/bin/bash
java -version

if [ $? -ne 0  ];then
	echo "--------------请先安装jdk,退出脚本------------"
	exit
fi

zkServer.sh status

if [ $? -ne 0  ];then
	echo "--------------请先安装zookeeper,退出脚本------------"
	exit
fi

INSTALL_PATH=$1
if [ ! $INSTALL_PATH ];then
	INSTALL_PATH="/usr/local/kafka"
fi

#kafka架包下载路径,不传默认ftp://ftpUser:123456@175.178.190.189/kafka/kafka_2.13-3.3.1/kafka_2.13-3.3.1.tgz
DOWNLOAD_URL=$2
if [ ! $DOWNLOAD_URL ];then
	DOWNLOAD_URL="ftp://ftpUser:123456@175.178.190.189/kafka/kafka_2.13-3.3.1/kafka_2.13-3.3.1.tgz"
fi

#kafka端口号
KAFKA_PORT=$3

if [ ! $KAFKA_PORT  ];then
	KAFKA_PORT=9092
fi

#获取公网ip
ip=`curl ident.me`

#zookeeper连接信息
ZOOKEEPER_INFO=$4
if [ ! $ZOOKEEPER_INFO ];then
 ZOOKEEPER_INFO=$ip:2181
fi

#如果文件夹不存在，创建文件夹
if [ ! -d $INSTALL_PATH ];then
   mkdir $INSTALL_PATH
fi

cd $INSTALL_PATH

if [ ! -d  $INSTALL_PATH/data ];then
        mkdir $INSTALL_PATH/data
fi

#wget下载文件
wget $DOWNLOAD_URL

##获取文件名
FILENAME=${DOWNLOAD_URL##*/};

#判断当前文件是什么压缩包
if [ ${FILENAME##*.} = gz ];then
  TEMP=${FILENAME%.*}
    if [ ${TEMP##*.} = tar ];then
        tar -zxvf $FILENAME -C $INSTALL_PATH
    else
        unzip  $FILENAME -d  $INSTALL_PATH
    fi
elif [ ${FILENAME##*.} = zip ];then
    unzip  $FILENAME -d  $INSTALL_PATH
elif [ ${FILENAME##*.} = tgz ];then
    tar -zxvf $FILENAME -C $INSTALL_PATH
fi

#删除安装包
rm -rf $INSTALL_PATH/$FILENAME

#获取解压后当前目录下的文件名
NEW_FILENAME=`ls -ll $INSTALLPATH |grep kafka|head -n 1|awk '{print $9}'`;

if [ ! $NEW_FILENAME ];then
  echo "解压失败，获取不到解压后的文件名，退出脚本";
  exit
fi

cd $NEW_FILENAME/config

#修改kafka配置信息
sed -i "/^.*zookeeper.connect=localhost:2181.*$/a    zookeeper.connect=$ZOOKEEPER_INFO" server.properties
sed -i "N;/\n.*zookeeper.connect=$ZOOKEEPER_INFO.*/!P;D" server.properties

sed -i "/^.*log.dirs=\/tmp\/kafka-logs.*$/a    log.dirs=$INSTALL_PATH\/data\/kafka-logs" server.properties
sed -i "N;/\n.*\/data\/kafka-logs.*/!P;D" server.properties

sed -i '$a\listeners=PLAINTEXT://0.0.0.0:'$KAFKA_PORT'' server.properties

sed -i '$a\advertised.listeners=PLAINTEXT://'$ip':'$KAFKA_PORT'' server.properties


cd /etc/profile.d/

#配置kafka环境变量
#创建kafka_env.sh文件并配置环境变量
#先判断文件是否已经存在，若存在先删除
if [ -f kafka_env.sh ];then
	rm -rf kafka_env.sh;
fi

#配置kafka环境变量
cat >>/etc/profile.d/kafka_env.sh<<EOF 
export KAFKA_HOME=$INSTALL_PATH/$NEW_FILENAME
export PATH=\$KAFKA_HOME/bin:\$PATH
EOF

#重启/ect/profile环境
source /etc/profile

#启动kafka
kafka-server-start.sh -daemon $INSTALL_PATH/$NEW_FILENAME/config/server.properties 

if [ $? -ne 0 ]; then
    echo "kafka启动失败，请排查原因，退出脚本";
    exit;
else
    echo "kafka 启动成功，请稍后手动登录云服务器,在安全组中放通$KAFKA_PORT端口";
fi


